import { createToast } from '../../common/toast.js';
import { generateNewUrl } from '../../common/url-handler.js';
import { createSwitchLayout } from './switch-layout.js';

export function initializeSwitchPage() {
    const sendMessageId = document.getElementById("go");
    const openOptionsBtn = document.getElementById("openOptions");
    let clusterControl, namespaceControl;

    function loadSelectOptions() {
        chrome.storage.local.get(['namespaceOptions', 'clusterOptions'], function(result) {
            const clusters = result.clusterOptions || [];
            const namespaces = result.namespaceOptions || [];

            if (!clusterControl) {
                clusterControl = createSwitchLayout('clusterInput', 'clusterDropdown', clusters);
            } else {
                clusterControl.updateOptions(clusters);
            }

            if (!namespaceControl) {
                namespaceControl = createSwitchLayout('namespaceInput', 'namespaceDropdown', namespaces);
            } else {
                namespaceControl.updateOptions(namespaces);
            }

            clusterControl.setValue('');
            namespaceControl.setValue('');
        });
    }

    // 监听配置更新消息
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.action === 'optionsUpdated') {
            loadSelectOptions();
        }
    });

    // 初始加载选项
    loadSelectOptions();

    // go 按钮点击事件
    if (sendMessageId) {
        sendMessageId.onclick = function() {
            if (!clusterControl || !namespaceControl) {
                createToast("未找到选择框！", 'error');
                return;
            }
            const selectedNamespace = namespaceControl.getValue();
            const selectedCluster = clusterControl.getValue();
            
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                const currentTab = tabs[0];
                const currentUrl = currentTab.url;

                const result = generateNewUrl(currentUrl, selectedCluster, selectedNamespace);
                
                if (!result.success) {
                    createToast(result.error, 'error');
                    return;
                }

                console.log("新URL：", result.url);
                chrome.tabs.update(currentTab.id, {url: result.url});
                createToast("正在切换集群和命名空间...", 'success');
            });
        };
    }

    if (openOptionsBtn) {
        openOptionsBtn.onclick = function() {
            chrome.runtime.openOptionsPage();
        };
    }
} 